<template>
  <Modal v-model="open" width="80%">
    <div slot="header" class="header-bar">
      <Icon type="ios-analytics" size="18"></Icon>
      <b>线路调压运行分析</b>
    </div>
    <div slot="footer"></div>
    <Button slot="close" type="error" size="small" icon="md-close"></Button>

    <Tabs v-model="activeTab" type="card" :animated="true">
      <TabPane name="UBA" label="电压分析">
        <div class="tiaoya">
          <div class="filter">
            <div class="item">
              <label>起始时间：</label>
              <DatePicker v-model="startDate" type="date" style="width: 110px" :clearable="false" :options="startOption"></DatePicker>
            </div>
            <div class="item">
              <Checkbox v-model="hasEndDate">终止时间：</Checkbox>
              <DatePicker v-model="endDate" type="date" style="width: 110px" :clearable="false" :options="endOption" :disabled="!hasEndDate"></DatePicker>
            </div>
            <div class="item">
              <label>电压下限：</label>
              <InputNumber v-model="minUb" :step="0.01"></InputNumber>
            </div>
            <div class="item">
              <label>电压上限：</label>
              <InputNumber v-model="maxUb" :step="0.01"></InputNumber>
            </div>
            <div class="item">
              <Button type="info" @click="getAnalysisData('Ub')">分析</Button>
            </div>
          </div>
          <Row :gutter="8">
            <Col span="18">
              <div class="panel">
                <div class="title">曲线信息</div>
                <div class="chart" :style="{ height: height.chart +'px' }">
                  <div class="chart-panel" ref="chart1"></div>
                </div>
                <div class="chart" :style="{ height: height.chart +'px' }">
                  <div class="chart-panel" ref="chart2"></div>
                </div>
              </div>
            </Col>
            <Col span="6">
              <div class="panel" :style="{ height: (height.chart * 2 + 22) +'px' }">
                <div class="title">统计信息</div>
                <ul class="count">
                  <li><label>平均电压：</label>{{ analysisDataUb.avgValue }} kV</li>
                  <li><label>最大电压：</label>{{ analysisDataUb.maxValue }} kV</li>
                  <li><label>最大值时间：</label>{{ analysisDataUb.maxTime }}</li>
                  <li><label>最小电压：</label>{{ analysisDataUb.minValue }} kV</li>
                  <li><label>最小值时间：</label>{{ analysisDataUb.minTime }}</li>
                  <li><label>合格率：</label>{{ analysisDataUb.okRate }}</li>
                  <li><label>调整次数：</label>{{ analysisDataUb.switchCount }}</li>
                </ul>
              </div>
            </Col>
          </Row>
          <Row>
            <div class="panel" :style="{ height: height.tarea +'px' }">
              <div class="title">电容器投切信息</div>
              <Input type="textarea" :value="swithMessUb" readonly></Input>
            </div>
          </Row>
        </div>
      </TabPane>
      <TabPane name="COS" label="功率因数分析">
        <div class="tiaoya">
          <div class="filter">
            <div class="item">
              <label>起始时间：</label>
              <DatePicker v-model="startDate" type="date" style="width: 110px" :clearable="false" :options="startOption"></DatePicker>
            </div>
            <div class="item">
              <Checkbox v-model="hasEndDate">终止时间：</Checkbox>
              <DatePicker v-model="endDate" type="date" style="width: 110px" :clearable="false" :options="endOption" :disabled="!hasEndDate"></DatePicker>
            </div>
            <div class="item">
              <label>功率因数下限：</label>
              <InputNumber v-model="minCos" :step="0.01"></InputNumber>
            </div>
            <div class="item">
              <label>功率因数上限：</label>
              <InputNumber v-model="maxCos" :step="0.01"></InputNumber>
            </div>
            <div class="item">
              <Button type="info" @click="getAnalysisData('cos')">分析</Button>
            </div>
          </div>
          <Row :gutter="8">
            <Col span="18">
              <div class="panel">
                <div class="title">曲线信息</div>
                <div class="chart" :style="{ height: height.chart +'px' }">
                  <div class="chart-panel" ref="chart3"></div>
                </div>
                <div class="chart" :style="{ height: height.chart +'px' }">
                  <div class="chart-panel" ref="chart4"></div>
                </div>
              </div>
            </Col>
            <Col span="6">
              <div class="panel" :style="{ height: (height.chart * 2 + 22) +'px' }">
                <div class="title">统计信息</div>
                <ul class="count">
                  <li><label>平均功率因数：</label>{{ analysisDataCos.avgValue }}</li>
                  <li><label>最大功率因数：</label>{{ analysisDataCos.maxValue }}</li>
                  <li><label>最大值时间：</label>{{ analysisDataCos.maxTime }}</li>
                  <li><label>最小功率因数：</label>{{ analysisDataCos.minValue }}</li>
                  <li><label>最小值时间：</label>{{ analysisDataCos.minTime }}</li>
                  <li><label>合格率：</label>{{ analysisDataCos.okRate }}</li>
                  <li><label>调整次数：</label>{{ analysisDataCos.switchCount }}</li><br />
                  <li><b style="color: #ed4014;">注：</b>功率因数大于0为正向供电</li>
                  <li><b style="padding: 0 10px;">&nbsp;</b>功率因数小于0为反向供电</li>
                </ul>
              </div>
            </Col>
          </Row>
          <Row>
            <div class="panel" :style="{ height: height.tarea +'px' }">
              <div class="title">电容器投切信息</div>
              <Input type="textarea" :value="swithMessCos" readonly></Input>
            </div>
          </Row>
        </div>
      </TabPane>
      <TabPane name="DET" label="详细信息">
        <div class="tiaoya">
          <div class="filter">
            <div class="item">
              <label>数据类型：</label>
              <Select v-model="detailType" style="width: 90px">
                <Option value="Ub">电压</Option>
                <Option value="cos">功率因数</Option>
              </Select>
            </div>
            <div class="item">
              <label>起始时间：</label>
              <DatePicker v-model="startDate" type="date" style="width: 110px" :clearable="false" :options="startOption"></DatePicker>
            </div>
            <div class="item">
              <Checkbox v-model="hasEndDate">终止时间：</Checkbox>
              <DatePicker v-model="endDate" type="date" style="width: 110px" :clearable="false" :options="endOption" :disabled="!hasEndDate"></DatePicker>
            </div>
            <div class="item" v-if="detailType === 'Ub'">
              <label>电压下限：</label>
              <InputNumber v-model="minUb" :step="0.01"></InputNumber>
            </div>
            <div class="item" v-if="detailType === 'Ub'">
              <label>电压上限：</label>
              <InputNumber v-model="maxUb" :step="0.01"></InputNumber>
            </div>
            <div class="item" v-if="detailType === 'cos'">
              <label>功率因数下限：</label>
              <InputNumber v-model="minCos" :step="0.01"></InputNumber>
            </div>
            <div class="item" v-if="detailType === 'cos'">
              <label>功率因数上限：</label>
              <InputNumber v-model="maxCos" :step="0.01"></InputNumber>
            </div>
            <div class="item">
              <Button type="info" @click="getAnalysisReport">查询</Button>
            </div>
            <div class="item">
              <Button type="default" @click="exportAnalysisReport">导出列表</Button>
            </div>
          </div>
          <Row :gutter="8">
            <Col span="18">
              <div class="panel">
                <div class="title">数据报表</div>
                <Table border :columns="detailReportColumn" :data="detailReportData" :height="height.table" :loading="detailLoading" ref="table"></Table>
              </div>
            </Col>
            <Col span="6">
              <div class="panel" :style="{ height: (height.table + 17) +'px' }">
                <div class="title">统计信息</div>
                <ul class="count" v-if="detailType === 'Ub'">
                  <li><label>平均电压：</label>{{ detailData.avgValue }} kV</li>
                  <li><label>最大电压：</label>{{ detailData.maxValue }} kV</li>
                  <li><label>最大值时间：</label>{{ detailData.maxTime }}</li>
                  <li><label>最小电压：</label>{{ detailData.minValue }} kV</li>
                  <li><label>最小值时间：</label>{{ detailData.minTime }}</li>
                  <li><label>合格率：</label>{{ detailData.okRate }}</li>
                  <li><label>调整次数：</label>{{ detailData.switchCount }}</li>
                </ul>
                <ul class="count" v-else>
                  <li><label>平均功率因数：</label>{{ detailData.avgValue }}</li>
                  <li><label>最大功率因数：</label>{{ detailData.maxValue }}</li>
                  <li><label>最大值时间：</label>{{ detailData.maxTime }}</li>
                  <li><label>最小功率因数：</label>{{ detailData.minValue }}</li>
                  <li><label>最小值时间：</label>{{ detailData.minTime }}</li>
                  <li><label>合格率：</label>{{ detailData.okRate }}</li>
                  <li><label>调整次数：</label>{{ detailData.switchCount }}</li><br />
                  <li><b style="color: #ed4014;">注：</b>功率因数大于0为正向供电</li>
                  <li><b style="padding: 0 10px;">&nbsp;</b>功率因数小于0为反向供电</li>
                </ul>
              </div>
            </Col>
          </Row>
        </div>
      </TabPane>
    </Tabs>
  </Modal>
</template>
<script>
import Chart from './chart';
import Ajax from '../ajax';
import { getStyle } from '@/utils/assist';
import fecha from '@/utils/date';
export default {
  name: 'TiaoyaModal',
  data () {
    return {
      devId: 0,
      open: false,
      activeTab: 'UBA',
      startDate: new Date(),
      endDate: '',
      hasEndDate: false,
      startOption: {
        disabledDate (date) {
          return date && date.valueOf() > Date.now();
        }
      },
      height: {
        chart: 180,
        tarea: 100,
        table: 460
      },

      chartIns: [],

      minUb: 10.00,
      maxUb: 10.70,
      swithMessUb: '',
      analysisDataUb: {},

      minCos: 0.90,
      maxCos: 1.00,
      swithMessCos: '',
      analysisDataCos: {},

      detailType: 'Ub',
      detailLoading: true,
      detailData: {},
      detailReportData: [],
      detailReportColumn: [
        {
          type: 'index',
          width: 70,
          align: 'center'
        },
        {
          title: '时间',
          key: 't',
          width: 150
        },
        {
          title: '电压（kV）',
          key: 'u'
        },
        {
          title: '#1电容状态',
          key: '1'
        },
        {
          title: '#2电容状态',
          key: '2'
        },
        {
          title: '#3电容状态',
          key: '3'
        },
        {
          title: '已投容量（kVAR）',
          key: 'v',
          width: 150
        }
      ]
    };
  },
  computed: {
    endOption () {
      const minDate = this.startDate.valueOf();
      return {
        disabledDate (date) {
          return date && (date.valueOf() > Date.now() || date.valueOf() < minDate);
        }
      };
    }
  },
  watch: {
    activeTab (val) {
      if (val === 'UBA') {
        this.getAnalysisData('Ub');
      } else if (val === 'COS') {
        this.getAnalysisData('cos');
      } else {
        this.getAnalysisReport();
      }
    },
    hasEndDate (val) {
      if (val) {
        this.endDate = this.startDate;
      } else {
        this.endDate = '';
      }
    }
  },
  methods: {
    setDevId (devId) {
      this.devId = devId;

      this.swithMessUb = '';
      this.analysisDataUb = {};
      this.swithMessCos = '';
      this.analysisDataCos = {};
      this.detailData = {};
      // 重置一下时间，防止打开太慢
      this.startDate = new Date();
      this.hasEndDate = false;
      this.open = true;

      if (this.activeTab === 'UBA') {
        this.getAnalysisData('Ub');
      } else if (this.activeTab === 'COS') {
        this.getAnalysisData('cos');
      } else {
        this.getAnalysisReport();
      }
      // 注销上一次charts
      this.disposeCharts();
    },
    async getAnalysisData (stdCode) {
      if (this.endDate && this.endDate.valueOf() - this.startDate.valueOf() > 3600 * 24 * 31 * 1000) {
        this.$Message.warning('时间间隔不能大于30天！');
        return;
      }
      const reqData = await Ajax.GetTiaoyaAnalysis({
        devId: this.devId,
        stdcode: stdCode,
        startTime: fecha.format(this.startDate, 'yyyyMMdd'),
        endTime: this.endDate ? fecha.format(this.endDate, 'yyyyMMdd') : fecha.format(this.startDate, 'yyyyMMdd'),
        maxRange: stdCode === 'Ub' ? this.maxUb : this.maxCos,
        minRange: stdCode === 'Ub' ? this.minUb : this.minCos
      });
      if (stdCode === 'Ub') {
        this.analysisDataUb = reqData;
        this.chartIns.push(Chart.loadTiaoyaChart(this.$refs.chart1, [reqData.deviceHistory[0]], {
          title: reqData.resourceName + ' 电压分析曲线',
          unit: 'kV',
          max: this.maxUb,
          min: this.minUb
        }));
        this.chartIns.push(Chart.loadTiaoyaChart(this.$refs.chart2, [
          reqData.deviceHistory[1],
          reqData.deviceHistory[2],
          reqData.deviceHistory[3]
        ], {
          title: reqData.resourceName + ' 电容投切状态',
          // 取上一个图的开始时间和截止时间
          start: reqData.deviceHistory[0].dataList.length && reqData.deviceHistory[0].dataList[0][0],
          end: reqData.deviceHistory[0].dataList.length && reqData.deviceHistory[0].dataList[reqData.deviceHistory[0].dataList.length - 1][0],
          step: 'end' // 投切状态跳变
        }));
        this.swithMessUb = reqData.swithMessList.join('\n');
      } else {
        this.analysisDataCos = reqData;
        this.chartIns.push(Chart.loadTiaoyaChart(this.$refs.chart3, [reqData.deviceHistory[0]], {
          title: reqData.resourceName + ' 功率因数分析曲线',
          max: this.maxCos,
          min: this.minCos
        }));
        this.chartIns.push(Chart.loadTiaoyaChart(this.$refs.chart4, [
          reqData.deviceHistory[1],
          reqData.deviceHistory[2],
          reqData.deviceHistory[3]
        ], {
          title: reqData.resourceName + ' 电容投切状态',
          // 取上一个图的开始时间和截止时间
          start: reqData.deviceHistory[0].dataList.length && reqData.deviceHistory[0].dataList[0][0],
          end: reqData.deviceHistory[0].dataList.length && reqData.deviceHistory[0].dataList[reqData.deviceHistory[0].dataList.length - 1][0],
          step: 'end' // 投切状态跳变
        }));
        this.swithMessCos = reqData.swithMessList.join('\n');
      }
    },
    async getAnalysisReport () {
      if (this.endDate && this.endDate.valueOf() - this.startDate.valueOf() > 3600 * 24 * 31 * 1000) {
        this.$Message.warning('时间间隔不能大于30天！');
        return;
      }
      this.detailLoading = true;
      this.detailReportData = [];
      // 改变一下table column
      if (this.detailType === 'cos') {
        this.detailReportColumn[2].title = '功率因数';
      }
      const reqData = await Ajax.GetTiaoyaReport({
        devId: this.devId,
        stdcode: this.detailType,
        startTime: fecha.format(this.startDate, 'yyyyMMdd'),
        endTime: this.endDate ? fecha.format(this.endDate, 'yyyyMMdd') : fecha.format(this.startDate, 'yyyyMMdd'),
        maxRange: this.detailType === 'Ub' ? this.maxUb : this.maxCos,
        minRange: this.detailType === 'Ub' ? this.minUb : this.minCos
      });
      this.detailData = reqData;
      if (reqData.reportList) {
        reqData.reportList.forEach(entry => {
          this.detailReportData.push({
            t: entry[0],
            u: entry[1],
            1: entry[2],
            2: entry[3],
            3: entry[4],
            v: entry[5]
          });
        });
      }
      this.detailLoading = false;
    },
    exportAnalysisReport () {
      this.$refs.table.exportCsv({
        filename: this.detailData.resourceName + '-' +
                  fecha.format(this.startDate, 'yyyy年MM月dd日') +
                  (this.endDate ? ('-' + fecha.format(this.endDate, 'yyyy年MM月dd日')) : '') +
                  (this.detailType === 'Ub' ? '电压' : '功率因数') + '分析报表'
      });
    },
    calculateHeight () {
      const bodyH = parseFloat(getStyle(document.body, 'height'));
      if (bodyH <= 680) {
        this.height = {
          chart: 180,
          tarea: 100,
          table: 480
        };
      } else {
        this.height = {
          chart: bodyH * 0.22,
          tarea: bodyH * 0.2,
          table: bodyH * 0.22 * 2 + bodyH * 0.2 + 20
        };
      }
    },
    disposeCharts () {
      this.chartIns.forEach((entry, index) => {
        entry.dispose();
      });
      this.chartIns = [];
    },
    resizeCharts () {
      this.calculateHeight();
      this.chartIns.forEach((entry, index) => {
        entry.resize();
      });
    }
  },
  created () {
    this.calculateHeight();
  },
  mounted () {
    window.addEventListener('resize', this.resizeCharts);
  },
  beforeDestroy () {
    this.disposeCharts();
    window.removeEventListener('resize', this.resizeCharts);
  }
};
</script>
